<template>
  <div class="dict-container">
    <!-- 左侧字典类型列表 -->
    <div class="dict-type-list">
      <DynamicTable
        row-key="id"
        header-title="字典管理"
        :data-request="Api.systemDictType.dictTypeList"
        :columns="columns"
        bordered
        size="small"
        :row-class-name="getRowClassName"
        :custom-row="customRow"
      >
        <template #toolbar>
          <a-button
            type="primary"
            @click="openMenuModal({})"
          >
            新增字典
          </a-button>
        </template>
      </DynamicTable>
    </div>
    
    <!-- 右侧字典项列表 -->
    <div class="dict-item-list">
      <div class="dict-item-header">
        <h4>{{ selectedDictType ? `字典项列表: ${selectedDictType.name}` : '请选择字典' }}</h4>
        <div class="dict-item-header-actions">
          <a-input-search
            v-if="selectedDictType"
            placeholder="搜索字典项"
            style="width: 200px; margin-right: 8px;"
            @search="handleSearchDictItem"
          />
          <a-button 
            type="primary" 
            size="small"
            :disabled="!selectedDictType"
            @click="openDictItemModal({typeId: selectedDictTypeId})"
          >
            新增字典项
          </a-button>
        </div>
      </div>
      
      <DictItemTable
        v-if="selectedDictType"
        row-key="id"
        :data-source="dictItemList"
        :columns="dictItemColumnsWithAction"
        bordered
        size="small"
        :immediate="false"
        :search="false"
        :show-tool-bar="false"
        :pagination="dictItemPagination"
        
        ref="dictItemTableRef"
      >
       
      </DictItemTable>
      
      <div v-else class="empty-dict-items">
        <a-empty description="请先选择左侧字典" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, h, getCurrentInstance, onMounted, nextTick, computed } from 'vue';
  import { baseColumns as dictItemColumns } from '../dict-item/columns';
  import {
    baseColumns,
    searchFormSchema,
    type TableListItem,
    type TableColumnItem,
  } from './columns';
  import { baseSchemas } from './formSchemas';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { baseSchemas as dictItemSchemas } from '../dict-item/formSchemas';

  // 声明ApiDictResponse接口，用于处理API返回的字典项数据
  interface ApiDictResponse {
    items: any[];
    meta?: {
      totalItems: number;
    };
    [key: string]: any;
  }

  defineOptions({
    name: 'SystemDict',
  });

  // 获取全局属性
  const app = getCurrentInstance();
  const $auth = app?.appContext.config.globalProperties.$auth;

  const dictTypeList = ref<any[]>([]);
  const dictItemList = ref<any[]>([]);
  const dictItemLoading = ref<boolean>(false);
  const selectedDictType = ref<TableListItem | null>(null);
  const selectedDictTypeId = ref<string | null>(null);
  const dictItemPagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: (page: number, pageSize: number) => {
      dictItemPagination.value.current = page;
      dictItemPagination.value.pageSize = pageSize;
      if (selectedDictTypeId.value) {
        loadDictItems(selectedDictTypeId.value);
      }
    }
  });

  const [DynamicTable, dynamicTableInstance] = useTable({
    formProps: {
      schemas: searchFormSchema,
    },
  });

  // 创建右侧字典项表格实例
  const [DictItemTable, dictItemTableInstance] = useTable({
    formProps: {
      schemas: [],
    },
  });

  const [showModal] = useFormModal();

  // 搜索关键词
  const searchKeyword = ref('');

  /**
   * @description 点击字典类型行
   */
  const handleRowClick = (record: TableListItem) => {
    console.log('点击了行:', record);
    selectedDictType.value = record;
    selectedDictTypeId.value = record.id;
    
    // 重置分页到第一页
    dictItemPagination.value.current = 1;
    
    // 重置搜索关键词
    searchKeyword.value = '';
    
    loadDictItems(record.id);
  };

  /**
   * @description 处理表格变化事件（排序、过滤）
   */
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    console.log('表格变化：', pagination, filters, sorter);
    
    // 更新分页参数
    dictItemPagination.value.current = pagination.current;
    dictItemPagination.value.pageSize = pagination.pageSize;
    
    // 保存排序参数
    const sortParams: Record<string, any> = {};
    if (sorter.field && sorter.order) {
      const order = sorter.order === 'ascend' ? 'ASC' : 'DESC';
      sortParams.sortBy = sorter.field;
      sortParams.sortOrder = order;
    }
    
    // 重新加载数据
    if (selectedDictTypeId.value) {
      loadDictItems(selectedDictTypeId.value, sortParams);
    }
  };

  /**
   * @description 加载字典项
   */
  const loadDictItems = async (typeId: string, extraParams: Record<string, any> = {}) => {
    dictItemLoading.value = true;
    try {
      // 加载字典类型列表（如果尚未加载）
      if (dictTypeList.value.length === 0) {
        const data = await Api.systemDictType.dictTypeGetAll();
        dictTypeList.value = data.map((n) => ({ label: n.name, value: n.id, code: n.code }));
      }
      
      // 获取分页参数
      const { current, pageSize } = dictItemPagination.value;
      
      // 请求后端分页数据
      const response = await Api.systemDictItem.dictItemList({
        typeId,
        index: current,
        pageSize: pageSize,
        ...extraParams
      }) as ApiDictResponse;
      
      // 更新列表数据
      dictItemList.value = response.items || [];
      
      // 更新分页总数
      if (response.meta) {
        dictItemPagination.value.total = response.meta.totalItems || 0;
      }
    } finally {
      dictItemLoading.value = false;
    }
  };

  // 为DynamicTable组件提供数据请求函数
  const loadDictItemsRequest = async (params: Record<string, any>) => {
    
    if (!selectedDictTypeId.value) {
      return { items: [], meta: { totalItems: 0 } };
    }
    
    // 获取分页参数
    const { current, pageSize } = dictItemPagination.value;
    
    // 合并搜索参数
    const requestParams: Record<string, any> = {
      typeId: selectedDictTypeId.value,
      index: current,
      pageSize: pageSize,
      ...params
    };
    
    // 如果有搜索关键词，添加到请求参数
    if (searchKeyword.value) {
      requestParams.keyword = searchKeyword.value;
    }
    
    try {
      // 请求后端分页数据
      const response = await Api.systemDictItem.dictItemList(requestParams) as ApiDictResponse;
      
      // 更新分页总数
      if (response.meta) {
        dictItemPagination.value.total = response.meta.totalItems || 0;
      }
      
      return response;
    } catch (error) {
      console.error('加载字典项失败:', error);
      return { items: [], meta: { totalItems: 0 } };
    }
  };

  /**
   * @description 打开新增/编辑弹窗
   */
  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}字典`,
        width: '50%',
        onFinish: async (values) => {
          console.log('新增/编辑字典', values);
          if (record.id) {
            await Api.systemDictType.dictTypeUpdate({ id: record.id }, values);
          } else {
            await Api.systemDictType.dictTypeCreate(values);
          }

          dynamicTableInstance?.reload();
          
          // 如果编辑的是当前选中的字典，需要重新加载字典项
          if (selectedDictTypeId.value && selectedDictTypeId.value === String(record.id)) {
            loadDictItems(String(record.id));
          }
        },
      },
      formProps: {
        labelWidth: 120,
        schemas: baseSchemas,
      },
    });
    formRef?.setFieldsValue({
      ...record,
    });
  };
  
  /**
   * @description 打开新增/编辑字典项弹窗
   */
  const openDictItemModal = async (record: any) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}字典项`,
        width: '50%',
        onFinish: async (values) => {
          console.log('新增/编辑字典项', values);
          if (record.id) {
            await Api.systemDictItem.dictItemUpdate({ id: record.id }, values);
          } else {
            await Api.systemDictItem.dictItemCreate(values);
          }
          
          // 重新加载对应字典类型的字典项
          if (selectedDictTypeId.value) {
            loadDictItems(selectedDictTypeId.value);
          }
        },
      },
      formProps: {
        labelWidth: 120,
        schemas: dictItemSchemas,
      },
    });
    
    formRef?.updateSchema({
      field: 'typeId',
      componentProps: {
        options: dictTypeList.value,
        disabled: !!record.typeId,
      },
    });
    
    formRef?.setFieldsValue({
      ...record,
    });
  };
  
  const delDictItemConfirm = async (record: any) => {
    await Api.systemDictItem.dictItemDelete({ id: record.id });
    // 重新加载对应字典类型的字典项
    if (selectedDictTypeId.value) {
      loadDictItems(selectedDictTypeId.value);
    }
  };
  
  const delRowConfirm = async (record: TableListItem) => {
    await Api.systemDictType.dictTypeDelete({ id: record.id });
    dynamicTableInstance?.reload();
    
    // 如果删除的是当前选中的字典，清空右侧列表
    if (selectedDictTypeId.value === String(record.id)) {
      selectedDictType.value = null;
      selectedDictTypeId.value = null;
      dictItemList.value = [];
    }
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right' as const,
      actions: ({ record }) => [
        {
          label: '编辑',
          auth: {
            perm: 'system:dict-type:update',
            effect: 'disable',
          },
          onClick: () => openMenuModal(record),
        },
        {
          label: '删除',
          auth: 'system:dict-type:delete',
          popConfirm: {
            title: '你确定要删除吗？',
            placement: 'left',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
  
  const getRowClassName = (record: TableListItem) => {
    return selectedDictTypeId.value === String(record.id) ? 'dict-selected-row' : '';
  };

  // 使用customRow处理行点击事件
  const customRow = (record: TableListItem) => {
    return {
      onClick: () => {
        handleRowClick(record);
      }
    };
  };
  
  // 修复字典项操作按钮
  const dictItemColumnsWithAction = computed(() => [
    ...dictItemColumns,
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      fixed: 'right' as const,
      actions: ({ record }: { record: any }) => [
        {
          label: '编辑',
          auth: 'system:dict-item:update',
          onClick: () => openDictItemModal(record),
        },
        {
          label: '删除',
          auth: 'system:dict-item:delete',
          popConfirm: {
            title: '你确定要删除吗？',
            placement: 'left',
            onConfirm: () => delDictItemConfirm(record),
          },
        },
      ],
    },
  ]);

  /**
   * @description 搜索字典项
   */
  const handleSearchDictItem = (value: string) => {
    searchKeyword.value = value;
    // 重置到第一页
    dictItemPagination.value.current = 1;
    
    if (selectedDictTypeId.value) {
      const params: Record<string, any> = {};
      if (value) {
        params.label = value;
      }
      loadDictItems(selectedDictTypeId.value, params);
    }
  };

  // onMounted(async () => {
  //   // 等待表格渲染完成
  //   await nextTick();
    
  //   // 使用事件委托，将事件监听绑定到表格容器上
  //   const tableContainer = document.querySelector('.dict-type-list');
  //   if (tableContainer) {
  //     tableContainer.addEventListener('click', (event) => {
  //       // 获取最近的tr元素
  //       const rowElement = (event.target as HTMLElement).closest('tr.ant-table-row');
  //       if (!rowElement) return;
        
  //       // 如果点击的是操作按钮，不触发行点击事件
  //       if ((event.target as HTMLElement).closest('.ant-btn') || 
  //           (event.target as HTMLElement).closest('.ant-dropdown-trigger')) {
  //         return;
  //       }
        
  //       // 获取行数据的id
  //       const id = rowElement.getAttribute('data-row-key');
  //       if (id) {
  //         console.log('通过事件委托点击行:', id);
  //         // 通过id找到对应的记录
  //         const dataSource = dynamicTableInstance?.tableData;
  //         if (Array.isArray(dataSource)) {
  //           const record = dataSource.find(item => String(item.id) === id);
  //           if (record) {
  //             handleRowClick(record);
  //           }
  //         }
  //       }
  //     });
      
  //     console.log('已绑定表格容器点击事件');
  //   }
  // });
</script>

<style scoped>
.dict-container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.dict-type-list {
  flex: 1;
  min-width: 550px;
}

.dict-item-list {
  flex: 1;
  min-width: 550px;
  display: flex;
  flex-direction: column;
}

.dict-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.dict-item-header-actions {
  display: flex;
  align-items: center;
}

.dict-item-header h4 {
  margin: 0;
  font-size: 16px;
  color: #1890ff;
}

.empty-dict-items {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.empty-dict-items button {
  margin-top: 16px;
}
</style>

<style>
/* 全局样式，用于高亮选中行 */
.dict-selected-row {
  background-color: #e6f7ff !important;
}
</style>
